package com.pointi.emoConverterM;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.pointi.emoGatewayM.ConfigurationData;
import com.pointi.emoGatewayM.JDBC;
import com.pointi.emoTools.emoReceived;

public class ThreadController extends Thread
{
	//____________________________________________________________________________________________________
	// DEF
	
	private ConcurrentLinkedQueue<ThreadController> _Controller ;
	private ConcurrentLinkedQueue<ThreadConverter> _Converter ;
	private ConfigurationData conf_data ;
	private JDBC _JDBC ;
	
	//____________________________________________________________________________________________________
	// INIT

	public ThreadController(ConcurrentLinkedQueue<ThreadController> inThread)
	{
		_Controller = inThread ;
	}

	public void start(JDBC inJDBC, ConfigurationData inConf_data)
	{
		conf_data = inConf_data ;
		_JDBC = inJDBC ;
		_Controller.add(this) ;
		super.start();
	}
	
	//____________________________________________________________________________________________________
	// RUN // Controller //

	public void run()
	{
		try
		{
			ArrayList<String> _ReceivedFile = new ArrayList<String>() ;
			_Converter = new ConcurrentLinkedQueue<ThreadConverter>() ;
			int mCheckInterval = Integer.valueOf(conf_data.s_check_interval) ;
			int mConverterLimit = Integer.valueOf(conf_data.s_converter_limit) ;
			int mConverterCount = 0 ;
			int mListSize = 0 ;
			boolean loopHandler = true ;
			while (loopHandler)
			{
				_JDBC.fnGetReceivedList(_ReceivedFile) ;
				mListSize = _ReceivedFile.size() ;
				for(int i=0; i<mListSize; i++)
				{
					if (_Converter.isEmpty()) _Converter = new ConcurrentLinkedQueue<ThreadConverter>() ;
					mConverterCount = _Converter.size() ;
					if (mConverterCount < mConverterLimit)
					{
						String mCallKey = _ReceivedFile.get(0) ;
						_ReceivedFile.remove(mCallKey) ;
						emoReceived mReceived = _JDBC.fnGetReceivedInfo(mCallKey) ; // Get FilePath (Original & Target)
						new ThreadConverter(_Converter).start(_JDBC, Integer.valueOf(mCallKey), mReceived) ;
						// System.out.println("[GW][CVT] Add Converting Job | " + mReceived.fnGetOriginalName()) ;
					}
				}
				Thread.sleep(mCheckInterval) ;
			}
		}
		catch (Exception e) { e.printStackTrace() ; }
		_Controller.remove(this) ;
	}
	
	//____________________________________________________________________________________________________
	// EOC
}
